package com.elcl.widget.view.indictor.arrowIndictor;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import com.elcl.andbaselibrary.R;
import com.elcl.animation.AnimationConstant;

/**
 * Created by lichunlin on 17/6/26.
 * 箭头指向的arrow,点击箭头，朝向改变，并且进行回调
 */

public class ArrowIndictorImageView extends ImageView {

//    private static final int ARROW_INDICTOR_DEFAULT = R.mipmap.btn_arrow_down;
    private static final int ARROW_INDICTOR_DEFAULT = 0;

    public ArrowIndictorImageView(Context context) {
        super(context);
    }

    public ArrowIndictorImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ArrowIndictorImageView);
        Integer arrowRecourse = ta.getResourceId(R.styleable.ArrowIndictorImageView_arrow_recourse, ARROW_INDICTOR_DEFAULT);
        ta.recycle();

        init(arrowRecourse);
    }

    public ArrowIndictorImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ArrowIndictorImageView);
        Integer arrowRecourse = ta.getResourceId(R.styleable.ArrowIndictorImageView_arrow_recourse, ARROW_INDICTOR_DEFAULT);
        ta.recycle();

        init(arrowRecourse);
    }

    private boolean isExpandable = false;//是否展开
    public void init(Integer arrowRecourse) {
        setImageResource(arrowRecourse);
        setPadding(10, 10, 10, 10);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onArrowClickListener();
            }
        });
    }

    //点击箭头执行动画+回调
    private void onArrowClickListener() {
        if (isExpandable) {//展开，点击后收缩
            onArrowClick.onClickBack();
        } else {//点击后展开
            onArrowClick.onClickExpandable();
        }
        isExpandable = !isExpandable;
        startRoatateAnimation();
    }

    //执行动画
    private void startRoatateAnimation() {
        float startDegree = 0f;
        float endDegree = 180f;

        if (isExpandable) {//展开
            startDegree = 0f;
            endDegree = 180f;
        } else {//收缩
            startDegree = 180f;
            endDegree = 0f;
        }

        ObjectAnimator animator = ObjectAnimator.ofFloat(this, AnimationConstant.ROTATION, startDegree, endDegree);
        animator.setDuration(300);
        animator.getTarget();
        animator.start();
    }

    private OnArrowClick onArrowClick;

    public void setOnArrowClickListener(OnArrowClick onArrowClick) {
        this.onArrowClick = onArrowClick;
    }

}
